const mongoose = require('mongoose')
const {Schema} = mongoose
// 连接mongodb数据库
mongoose.connect('mongodb://127.0.0.1:27017/bilibili')

// 设置回调
// once 一次 事件回调函数只执行一次
// mongoose.connection.once('open', () => {  //连接成功的回调
//   console.log('连接成功')
// })
mongoose.connection.once('open', async () => {  //连接成功的回调
  console.log('连接成功')
  // 外网文档写法
  let bookSchema = new Schema({
    name:String,
    author: String,
    price: Number
  })
  // 添加方法  类似 类
  bookSchema.methods.sayHello = function(){
    const greeting = this.name ? 'book name is ' + this.name + 'author is ' + this.author : 'I don\'t have a name';
    console.log(greeting);
  }
  // 'book' 就是集合名，mongose会使用集合名的复数 来创建集合，数据库中存的就是 books
  let bookModel = mongoose.model('book', bookSchema)
  const result = new bookModel({
    name: 'JavaScript高级程序设计',
    author: 'Nicholas C. Zakas',
    price: 99.9
  })
 

  // 提交保存到mongodb数据库
  // await result.save()
  // result.sayHello()
  // 查询
  const books = await bookModel.find()
  console.log(books)

})
mongoose.connection.on('error', () => {  //连接失败的回调
  console.log('连接失败')
})
mongoose.connection.on('close', () => {  //连接关闭的回调
  console.log('连接关闭')
})